﻿using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace ybx_caller
{
    public static class NetworkUtils
    {
        private static readonly string[] BlackList = new string[]
        {
        "virtual", "pseudo", "meta"
        };

        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (ni.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                    ni.OperationalStatus == OperationalStatus.Up &&
                    !BlackList.Any(blackItem => ni.Description.ToLowerInvariant().Contains(blackItem)))
                {
                    var ipProperties = ni.GetIPProperties();
                    var ipAddress = ipProperties.UnicastAddresses
                        .Where(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)
                        .Select(ua => ua.Address.ToString())
                        .FirstOrDefault();

                    if (ipAddress != null)
                        return ipAddress;
                }
            }

            // 如果没有找到合适的外部IP，返回本地地址
            return "127.0.0.1";
        }
    }
}
